from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = datetime.now()
        self.friends = []
        self.books = []

class Book(object):
    def __init__(self, title, author):
        self.title = title
        self.author = author  # 用来代替MySQL中的外键关系

class BookSchema(Schema):
    title = fields.String()
    # 使用lambda匿名函数，使只有在使用author时才会找UserSchema对象，不然可能出现先后调用，导致对象找不到的情况出现
    # 用来序列化外键对象，可以将外键对象按照指定的格式进行序列化，并且外键指定的格式可以完成任何支持的marshmallow操作
    author = fields.Nested(lambda: UserSchema())

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime(format='%Y-%m-%d %H:%H:%S')

@app.route("/")
def index():
    #多对一，一对一
    user0 = User(name="南派三叔", email="sanshu@163.com")
    book = Book(title="盗墓笔记", author=user0)
    bs = BookSchema()
    book_data = bs.dump(book)
    print(book_data)
    """
    打印结果：
    {
        'author':
            {
                'created_at': '2021-03-05 22:22:45',
                'email': 'sanshu@163.com',
                'name': '南派三叔'
            },
        'title': '盗墓笔记'
    }
    """

    return "hello"

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0" , port=5998)
